import { FakeHeaders } from "../utils";
import { IMediaType, IMedia, IData, IError } from "../_type";

const MP4_VIDEO_TYPE = "mp4";

export default async (url: string): Promise<IData | IError> => {
  try {
    const html = await fetch(url, {
      headers: FakeHeaders,
    }).then((res) => res.text());

		console.log(html);
    // Extract video URLs
    const urlsJSONMatch = html.match(/"backupUrls":(\[.+?\])/);
    if (!urlsJSONMatch || urlsJSONMatch.length !== 2) {
      throw new Error("Failed to parse body");
    }
    const urls: string[] = JSON.parse(urlsJSONMatch[1]);

    const parsedUrl = new URL(url);
    if (!parsedUrl.host) {
      throw new Error("Invalid URL");
    }

    const medias: IMedia[] = [];
    for (let i = 0; i < urls.length; i++) {
      const u = urls[i];
      if (!u.includes(MP4_VIDEO_TYPE)) {
        medias.push({
          type: IMediaType.Image,
          data: u
        })
      } else {
        medias.push({
          type: IMediaType.Video,
          data: u
        })
      }
    }

    return {
      ok: true,
      data: medias
    };
  } catch (error) {
    return {
      ok: false,
      data: (error as any).message,
    };
  }
};
